import Vue from 'vue'
import Vuex from 'vuex'


Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        websock: null,
        eventlist: []
    },
    getters: {
        onEvent(state) {
            return function(method) {
                let index = state.eventlist.map((eb) => { return eb.method }).indexOf(method);
                if (state.eventlist.length > 0 && index >= 0) {
                    let result = Object.assign({}, state.eventlist[index]);
                    state.eventlist.splice(index, 1);
                    return result.data;
                }
                return null;
            }
        }
    },
    mutations: {
        WEBSOCKET_INIT(state, url) {
            state.websock = new WebSocket(url);
            state.websock.onopen = function() {
                console.log("连接成功！");
            }
            state.websock.onmessage = function(callBack) {
                console.log("ws接收！");

                let data = JSON.parse(callBack.data)
                data.time = new Date()

                var receive = [];
                var type = 0;
                var length = 0;

                state.eventlist.push({
                        // method: methodStr,
                        data: data
                    })
                    // this.$notify({
                    //     title: '标题名称',
                    //     message: '这是一条不会自动关闭的消息',
                    //     duration: 0
                    // });
            }
            state.websock.οnerrοr = function(e) { //错误
                console.log("ws错误!");
                console.log(e);
            }
            state.websock.onclose = function(e) { //关闭
                console.log("ws关闭！");
                console.log(e);
            }
            state.websock.binaryType = "arraybuffer";
            //发送心跳包
            // setInterval(function() {
            //     console.log("ws发送心跳！");
            //     var heart = {
            //         type: 5,
            //         method: "",
            //         jsonData: {}
            //     };
            //     state.websock.send(makeByte(heart));
            // }, 30000)
        },
        WEBSOCKET_SEND(state, p) {
            console.log("ws发送！");
            state.websock.send(makeByte(p));
        },
        WEBSOCKET_CLOSE(state) {
            state.websock.close()
        }
    },
    actions: {
        WEBSOCKET_INIT({ commit }, url) {
            commit('WEBSOCKET_INIT', url)
        },
        WEBSOCKET_SEND({ commit }, p) {
            p.type = 3;
            commit('WEBSOCKET_SEND', p)
        },
        WEBSOCKET_CLOSE({ commit }) {
            commit('WEBSOCKET_CLOSE')
        }
    }
})